package com.sjh.rlock;

import com.sjh.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/redisson")
public class RLockTestController {

    @Autowired
    private DistributedRLock distributedRLock;

    @RequestMapping("/test")
    public void redissonTest() {
        String key = Constant.R_LOCK + "test";
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean res = false;
                    try {
                        System.err.println("=============线程开启============" + Thread.currentThread().getName());
                        res = distributedRLock.tryLock(key); // 尝试获取锁，等待5秒，自己获得锁后一直不解锁则10秒后自动解锁
                        if (res) {
                            System.out.println("线程:" + Thread.currentThread().getName() + ",获取到了锁");
                            Thread.sleep(100); // 获得锁之后可以进行相应的处理
                            System.err.println("======获得锁后进行相应的操作======" + Thread.currentThread().getName());
                            System.err.println("=============================" + Thread.currentThread().getName());
                        } else {
                            System.err.println("获取锁失败");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (res) {
                            distributedRLock.unlock(key);
                        }
                    }
                }
            });
            t.start();
        }
    }
}